package com.yuntianshi.service.impl;

import com.yuntianshi.common.PageResult;
import com.yuntianshi.dao.UserDao;
import com.yuntianshi.dao.UserSettingDao;
import com.yuntianshi.pojo.User;
import com.yuntianshi.service.UserSettingService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class  UserSettingServiceImpl implements UserSettingService {

    @Autowired
    private UserSettingDao userSettingDao;

    @Autowired
    private UserDao userDao;

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        //        完成分页查询，基于MyBatis框架提供的分页助手插件完成
        if (queryString!=null&&queryString.length()>0){
            PageHelper.startPage(1,pageSize);
        }
        PageHelper.startPage(currentPage,pageSize);
        Page<User> page = userSettingDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(User user) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String password=bCryptPasswordEncoder.encode(user.getPassword());
//        System.out.println(password);
        user.setPassword(password);
        userSettingDao.add(user);
        User byUsername = userDao.findByUsername(user.getUsername());
        //设置权限
        userSettingDao.setUserAndRole(byUsername.getId());
    }

    @Override
    public List<User> findAll() {
        return userSettingDao.findAll();
    }

    @Override
    public void delete(Integer id) {
        //首先删除权限
        userSettingDao.deleteRoleByUserId(id);
        //然后删除员工信息
        userSettingDao.delete(id);
    }

    @Override
    public User findById(Integer id) {
        return userSettingDao.findById(id);
    }

    @Override
    public Integer getRoleByUsername(String username) {
        //获取用户基本信息
        User user = userDao.findByUsername(username);
        //根据用户id获取权限
        Integer id=userSettingDao.getRoleId(user.getId());
        return id;
    }

    @Override
    public void edit(User user) {
        if (user.getPassword()!=null){
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String password=bCryptPasswordEncoder.encode(user.getPassword());
//        System.out.println(password);
            user.setPassword(password);
        }
        userSettingDao.edit(user);
    }

    @Override
    public User findByUserName(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public void updatePassword(User user) {
        userSettingDao.edit(user);
    }
}
